//
//  TQQCloudTagView.swift
//  SwiftLearning
//  标签云
//  Created by 黄龙 on 2024/1/25.
//

import UIKit

//云标签
class TQQCloudTagView: UIView {
    let TAG_SPACE = 20.0//词条间距
    let MARGIN_LEFT = 15.0//左间距
    let MARGIN_TOP = 15.0//上间距
    private var _titleArr:[String] = []
    private var _colorArr:[UIColor] = []
    private var _fontArr:[UIFont] = []
    private var _rowHeight = 30.0 //行高

    var tapBlock:os_block_int?
    
    init(frame:CGRect,titleArr:[String],colorArr:[UIColor],fontArr:[UIFont],rowHeight:CGFloat){
        super.init(frame: frame)
        _titleArr.append(contentsOf: titleArr)
        _colorArr.append(contentsOf: colorArr)
        _fontArr.append(contentsOf: fontArr)
        _rowHeight = rowHeight
        
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
//随机生成不同的label标签
//        var mutiTitles:[String] = []
//        mutiTitles.append(contentsOf: _titleArr)
//也可以直接：
//        var mutiTitles = _titleArr //array赋值为值引用，对mutiTitles操作不会影响到_titleArr
        for perLabel in self.subviews{
            perLabel.removeFromSuperview()
        }
        
        var indexArr:[Int] = [] //存储序号，通过序号可以找到_titleArr对应的title，也能设定label的点击tag
        for i in 0 ..< _titleArr.count{
            indexArr.append(i)
        }
        var currentX = MARGIN_LEFT
        var currentY = MARGIN_TOP
        while(indexArr.count>0){
            var iTry = 0
            while(indexArr.count>0){ //随机取一合适的title生成label
                let itag = Int(arc4random_uniform(UInt32(indexArr.count))) //随机取出一标签
                let tagIndex = indexArr[itag]
                let text = _titleArr[tagIndex]
                let font = _fontArr[Int(arc4random_uniform(UInt32(_fontArr.count)))]
                let size = SwiftFunc.sizeWithText(text, font: font)
                if (currentX + size.width + TAG_SPACE > screen_W) {
                    iTry += 1
                    if iTry<=5{
                        NSLog("retry.continue[%d]%.1f", iTry,currentX)
                        continue; //超出宽度，继续找合适的词条
                    }else{
                        currentY += _rowHeight
                        if currentY + _rowHeight > self.bounds.height{ 
                            NSLog("retry.over:%.1f", currentY)
                            return //下一行已经放不下，则结束寻找
                        }else{
                            NSLog("retry.break:%.1f", currentY)
                            currentX = MARGIN_LEFT
                            break //找不到合适宽度的词条，说明要换行了，同时left重置
                        }
                    }
                }
                let label = UILabel()
                label.tag = tagIndex
                label.text = text
                label.textColor = _colorArr[Int(arc4random_uniform(UInt32(_colorArr.count)))]
                label.font = font
//                label.sizeToFit() //前面已经计算好了，无需再用
                let rect = CGRect(x: currentX, y: currentY, width: size.width, height: _rowHeight)
                label.frame = rect
                self.addSubview(label)
                label.isUserInteractionEnabled = true
                let tapLabel = UITapGestureRecognizer(target: self, action: #selector(onClickLabel(_:)))
                label.addGestureRecognizer(tapLabel)
                
                indexArr.remove(at: itag)
                currentX += size.width + TAG_SPACE
                break; //下一个词条
            }
        }
    }
    
    @objc func onClickLabel(_ sender:UITapGestureRecognizer){
        if let itag = sender.view?.tag{
            if let block = tapBlock{
                block(itag)
            }
        }
    }
    
}
